/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.grnt.buddy;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.grnt.dbcommon.IdExtractor;
import org.grnt.common.OptStatBean.OptStateException;
import org.grnt.dbcommon.DataControler.DataControlException;
import org.grnt.dbcommon.DataControler;
import static org.grnt.buddy.BuddiesContext.*;

/**
 *
 * It is a example servlet for illustrat how to implement add a buddy to a user
 * root group buddy semantic.
 * @author sayid
 */
public class AddBuddyToUserSlt extends HttpServlet{
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
	
	private Long    buddyId  = null;
	private String  alias    = null;
	private Long    parentId = null;
	private String  ownerName = null;
	private Long    ownerId  = null;
	private Long    userId   = null;
	private String  msg      = null;
	private String  loginName = null;

	private void output(HttpServletResponse response) throws IOException {
		response.setContentType("text/html");
		response.setHeader("Pragma", "No-cache");
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-cache");
		ServletOutputStream out = response.getOutputStream();
		out.println("<head><title>Just a basic servlet</title></head>");
		out.println("<body>");
		out.println("buddyId is :" + buddyId);
		out.println("<br/>");
		out.println("alias :" + alias);
		out.println("<br/>");
		out.println("parent id is:" + parentId);
		out.println("<br/>");
		out.println("owner name is:" + ownerName);
		out.println("<br/>");
		out.println("owner id is:" + ownerId);
		out.println("<br/>");
		out.println("user id is:" + userId);
		out.println("<br/>");
		out.println("user name is:" + loginName + "(alias equals to login name.)");
		out.println("<br/>");
		out.println("<H1>" + msg + "</H1>");
		out.println("</body>");
		out.close();
	}

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, OptStateException {
		ownerName = request.getParameter("ownerName");
		loginName = request.getParameter("loginName");

		ServletOutputStream out = response.getOutputStream();

		if((ownerName == null) || ("".equals(ownerName.trim()))) {
			msg = "owner user's name is null.";
			output(response);
			throw new ServletException(msg);
		}

		if((loginName == null) || ("".equals(loginName.trim()))) {
			msg = "entity user's name is null.";
			output(response);
			throw new ServletException(msg);
		}

		ownerName = ownerName.trim();
		loginName = loginName.trim();

		if ((ownerId = getUsersIndex().get(ownerName)) == null) {
			msg = "Here isn't the user with name " + ownerName;
			output(response);
			throw new ServletException(msg);
		}

		if ((userId = getUsersIndex().get(loginName)) == null) {
			msg = "Here isn't the user with name " + loginName;
			output(response);
			throw new ServletException(msg);
		}
		alias = loginName;
		UserBean user = getUsers().get(ownerId).getUserBean();
		parentId = user.getRootGroupId();

		try {
			buddyId = IdExtractor.nextId("buddy_id");

			AddBuddy buddyUpdater = new AddBuddy(buddyId
					, alias, parentId
					, ownerId
					, userId
					, false);
			DataControler.update(buddyUpdater);
			msg = "successful!";
		} catch (DataControlException ex) {
			msg = ex.getMessage();
			ex.printStackTrace();
		} finally {
			output(response);
			out.close();
		}
	}

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (OptStateException ex) {
			Logger.getLogger(AddBuddyToUserSlt.class.getName()).log(Level.SEVERE, null, ex);
			throw new ServletException(ex);
		}
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (OptStateException ex) {
			Logger.getLogger(AddBuddyToUserSlt.class.getName()).log(Level.SEVERE, null, ex);
			throw new ServletException(ex);
		}
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
